<template>
    <section class="section">
      <div class="luckBg">
        <div class="luckWhellBg">
          <div class="luckWhellBgMain rotateStyle" :style="{ transform: `rotate(${rotateAngle}deg)` }">
            <div v-for="(prize, i) in prizeList" :key="i" class="luckWhellSector" :style="prize.style2"></div>
          </div>
          <div class="truntable_bg" @click="prizeRoll" v-if="lang == 'zh'"></div>
          <div class="truntable_bg truntable_bg_en" @click="prizeRoll" v-if="lang == 'en'"></div>
          <div class="wheel-main">
            <div class="prize-list rotateStyle" :style="{ transform: `rotate(${rotateAngle}deg)` }">
              <div v-for="(prize, i) in prizeList" :key="i" class="prize-item" :style="prize.style">
                <div :class="{'xxcy':prize.prize_type == 3}" class="prize_text">{{ prize.prize_name }}</div>
                <div class="img" v-if="prize.prize_type !== 3 && lang == 'zh'">
                  <img :src="$baseUrl+prize.prize_img" style="width:90%"/>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="progress">
        <el-progress :text-inside="true" :stroke-width="25"  color="#ff5abf" :percentage="num" status="warning"  :format="percentage => $t('Lucky_Value')+' '+percentage/2"/>
        <span>{{user_info.prize_number}}/50</span>
      </div>

      <div class="carousel-box">
        <el-carousel v-if="prize_data.length > 0" :key="prize_data.length"   class="carousel" height="30px" direction="vertical" :autoplay="true" :loop="true" indicator-position="none" :interval="4000">
          <el-carousel-item v-for="item in prize_data" :key="item.id">
            <h3 v-if="lang == 'zh'" text="2xl" justify="center">恭喜 {{ item.nickname }} 抽中了 {{ item.prize_name }}</h3>
            <h3 v-if="lang == 'en'" text="2xl" justify="center">Congratulations to {{ item.nickname }} for winning a {{ item.prize_name }}</h3>
          </el-carousel-item>
        </el-carousel>
      </div>
      
    </section>

    <nav>
      <p :class="{active:!isNav}" @click="isNav = 0">{{ $t('Lottery_Rules') }}</p>
      <p :class="{active:isNav}" @click="isNav = 1">{{ $t('Lottery_details') }}</p>
    </nav>

    <div v-show="!isNav">
      <div class="tip" v-if="lang == 'zh'">
          <h3>活動規則</h3>
          <p>參與活動即視為您已閱讀並認可本活動規則，理解並願意接受本活動的約束。</p>

          <h3>活動玩法</h3>
          <ol>
              <li>參與抽獎1次需要消耗20積分，單日累計抽獎次數達到50次時，必得1張隨機金額的滿減券。</li>
              <li>滿減券有效期為1天，請盡快使用，可在儲值——滿減券中查看。</li>
              <li>注：若提前抽出滿減券，累計抽獎次數將會清零。</li>
          </ol>

          <h3>特別聲明</h3>
          <ol>
              <li>出於風險控制的原因，如發現用戶存在惡意作弊、惡意刷號、惡意攻擊，或其他非正規途徑獲取禮品等，本平台有權拒絕提供獎品，情節嚴重者有權追究法律責任；</li>
              <li>本平台可根據活動的實際情況，在法律允許的範圍內，對本活動的規則進行變動或調整，相關變動或調整將公佈在活動規則頁面上，並與公佈時間即時生效；</li>
              <li>因用戶操作不當或所在地區網絡故障、電信運營商故障等不能控制的原因導致用戶無法參與活動或失敗，平台不負法律或經濟責任。</li>
          </ol>
      </div>

      <div class="tip" v-if="lang == 'en'">
        <h3>Activity Rules</h3>
        <p>By participating in the activity, you are deemed to have read and accepted these rules, and you agree to abide by the constraints of this activity.</p>
        <h3>How to Play</h3>
        <ol>
            <li>Each lottery entry consumes 20 points. Once you accumulate 50 lottery entries in a single day, you are guaranteed to receive a random discount coupon.</li>
            <li>The discount coupon is valid for one day. Please use it as soon as possible. You can check it under "Stored Value" - "Discount Coupons".</li>
            <li>Note: If you draw a discount coupon in advance, your accumulated lottery entries will be reset to zero.</li>
        </ol>
        <h3>Special Statement</h3>
        <ol>
            <li>For risk control reasons, if users are found to engage in malicious cheating, malicious account farming, malicious attacks, or other improper means to obtain prizes, the platform reserves the right to refuse to provide the prize. In serious cases, the platform reserves the right to pursue legal responsibility.</li>
            <li>The platform may, within the scope of the law, make changes or adjustments to the rules of this activity based on actual circumstances. Any such changes or adjustments will be announced on the activity rules page and will take effect immediately upon publication.</li>
            <li>The platform will not be held legally or financially responsible if users are unable to participate in the activity or fail due to reasons beyond the platform’s control, such as improper user operations, regional network failures, or telecom operator issues.</li>
        </ol>
      </div>
    </div>

    <div v-show="isNav">
      <div class="recharge_content">
            <div class="title">
              <span class="flex-list">{{$t('prize')}}</span>
              <span class="flex-list">{{$t('data')}}</span>
            </div>
            <div class="main">
                <div class="main_line" v-for="item in awards_result_log_list" :key="item.id">
                    <span class="flex-list">{{ item.prize_name }}</span>
                    <span class="flex-list">{{ item.created_at }}</span>
                </div>
                <p class="isNull isNull_notext" v-if="awards_result_log_list.length == 0">{{$t('no_record')}}</p>
            </div>
        </div>
    </div>

    <div class="blocker2" @click="closeBox()" v-show="isShow"></div>
    <div class="img_box"  :class="{show:isShow}">
      <svg @click="closeBox()"  t="1726141262947" class="icon close_box" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4263" width="30" height="30"><path d="M240.512 180.181333l271.530667 271.488 271.530666-271.488a42.666667 42.666667 0 0 1 56.32-3.541333l4.010667 3.541333a42.666667 42.666667 0 0 1 0 60.330667l-271.530667 271.530667 271.530667 271.530666a42.666667 42.666667 0 0 1-56.32 63.872l-4.010667-3.541333-271.530666-271.530667-271.530667 271.530667-4.010667 3.541333a42.666667 42.666667 0 0 1-56.32-63.872l271.488-271.530666-271.488-271.530667a42.666667 42.666667 0 0 1 60.330667-60.330667z" fill="#e9e9e9" p-id="4264"></path></svg>
      <div class="top">
        <h1 v-if="goods_img !== ''">{{$t('Congratulations_earning')}} {{ goods }}</h1>
        <!-- <h1 v-if="goods_img == ''">謝謝參與，再接再厲</h1> -->
      </div>
      <img v-if="goods_img !== ''" width="350px" :src="$baseUrl+goods_img" alt="">
      <button @click="closeBox()" class="btn">{{ $t('confirm') }}</button>
    </div>
    
    <BindAccount :visible="visible" :handleClose='handleClose' :getUserInfo="getUserInfo" :fb_bind_show="fb_bind_show" :yh_bind_show="yh_bind_show" :gg_bind_show="gg_bind_show"/>
  
    <div v-if="lang == 'zh'">
      <Dialog :title="'faceBook绑定'" :title2="'faceBook是否綁定成功'" :cancel_title="'綁定失敗'" :sub_title="'綁定成功'" :visible="dialog_fb_bind" :handleClose='fb_bind_com' :paySubmit="fb_bind_com"/>
      <Dialog :title="'Yahoo绑定'" :title2="'Yahoo是否綁定成功'" :cancel_title="'綁定失敗'" :sub_title="'綁定成功'" :visible="dialog_yh_bind" :handleClose='yh_bind_com' :paySubmit="yh_bind_com"/>
      <Dialog :title="'Google绑定'" :title2="'Google是否綁定成功'" :cancel_title="'綁定失敗'" :sub_title="'綁定成功'" :visible="dialog_gg_bind" :handleClose='gg_bind_com' :paySubmit="gg_bind_com"/>
    </div>
      
    <div v-if="lang == 'en'">
      <Dialog :title="'facebook binding'" :title2="'Is facebook successfully bound?'" :cancel_title="'Binding failed'" :sub_title="'Binding successful'" :visible="dialog_fb_bind" :handleClose='fb_bind_com' :paySubmit="fb_bind_com"/>
      <Dialog :title="'Yahoo binding'" :title2="'Is Yahoo successfully bound?'" :cancel_title="'Binding failed'" :sub_title="'Binding successful'" :visible="dialog_yh_bind" :handleClose='yh_bind_com' :paySubmit="yh_bind_com"/>
      <Dialog :title="'Google binding'" :title2="'Is Google successfully bound?'" :cancel_title="'Binding failed'" :sub_title="'Binding successful'" :visible="dialog_gg_bind" :handleClose='gg_bind_com' :paySubmit="gg_bind_com"/>
    </div>
  </template>
  
<script setup>
import { ref, onMounted,reactive,watch, watchEffect } from 'vue';
import axios from '@/utils/api'
import { useUserInfoStore } from '@/store/modules/user_info/index';
import BindAccount from "@/components/UserCenter/bindAccount/index.vue"
import Dialog from "@/components/Dialog/index.vue"
const user_infoStore = useUserInfoStore();
const user_info = reactive(user_infoStore.userInfo)
console.log(user_infoStore,'user_infoStore');

const visible = ref(false)
	
const handleClose = () => {
	visible.value = false
};

let dialog_fb_bind = ref(false)
const fb_bind_show = ()=>{
	dialog_fb_bind.value = true
}
const fb_bind_com = ()=>{
	getUserInfo()
	dialog_fb_bind.value = false
}

let dialog_yh_bind = ref(false)
const yh_bind_show = ()=>{
	dialog_yh_bind.value = true
}
const yh_bind_com = ()=>{
	getUserInfo()
	dialog_yh_bind.value = false
}

let dialog_gg_bind = ref(false)
const gg_bind_show = ()=>{
    dialog_gg_bind.value = true
}
const gg_bind_com = ()=>{
    getUserInfo()
    dialog_gg_bind.value = false
}

let lang = ref('')
if(localStorage.getItem('lang') == 'en'){
    lang.value = 'en'
}else{
    lang.value = 'zh'
}

let num = ref(user_info.prize_number * 2)

watchEffect(() => {
    num.value = user_info.prize_number * 2
})
const getUserInfo = async () =>{
    const data = {
        user_id:user_info.id,
    }
    const list = await axios.post('/getUserInfo',data)
    user_infoStore.setUserinfo(list.data.user_info)
}

const prize_list = ref([])
const getPrizeList = async () =>{
    const list = await axios.get('/getPrizeList')
    prize_list.value = list.data

    prizeAddHtml();
}
getPrizeList()
  
  const CIRCLE_ANGLE = 360;
  const BIGSIZE = 24;
  const goods = ref('') //抽到的奖品
  const goods_img = ref('')//抽到的图片

  const angleList = ref([]);
  const prizeList = ref([]);
  const rotateAngle = ref(0);
  const isRotating = ref(false);
  const remainingAttempts = ref(1);
  
  const formatPrizeList = (list) => {
    const l = list.length;
    const average = CIRCLE_ANGLE / l;
    const half = average / 2;
    const rightBig = l === 2 ? '50' : '0';
    const heightBig = l <= 3 ? '100' : '50';
    const topBig = l === 3 ? '-50' : '0';
    const skewMain = l <= 2 ? 0 : -(l - 4) * 90 / l;
  
    return list.map((item, i) => {
      const angle = -(i * average + half);
      const bigAge = l > 2 ? i * 360 / l : '0';
      const style = `transform: rotate(${-angle}deg); width:${100 / l * 2}%; margin-left: -${100 / l}%; font-size:${BIGSIZE - l+2}px;`;
      const style2 = `transform: rotate(${bigAge}deg) skewY(${skewMain}deg); right:${rightBig * i}%; height:${heightBig}%; top:${topBig}%; width:${l === 1 ? 100 : 50}%; `;
      angleList.value.push(angle);
      return { ...item, style, style2 };
    });
  };
  
  const prizeAddHtml = () => {
    prizeList.value = formatPrizeList(prize_list.value);
  };
  
  async function prizeRoll() {
    if (isRotating.value) return;
    
    const res = await axios.post('/awards_result',{user_id:user_info.id})
    console.log(res);
    if(res.code == 200){
      const prize = prizeList.value.find(item => item.id === res.data.id);
      const index = prizeList.value.indexOf(prize);
      rotating(index); // 调用旋转函数
      
    }else if(res.code == 7017){
      if(lang.value == 'en'){
          ElMessage.warning('Your points are insufficient, please continue to work hard to sign in')
      }else{
          ElMessage.warning('您的積分不足，請繼續努力簽到')
      }
    }else if(res.code == 7021){
      visible.value = true
      if(lang.value == 'en'){
        ElMessage.warning('The points lottery can only be claimed by formal members. Please verify as a formal member')
      }else{
          ElMessage.warning(res.message)
      }
    }else{
      ElMessage.warning(res.message)
    }
  }

  let prize_type = ref(0)
  const rotating = (index) => {
    isRotating.value = true;
  
    const config = {
      duration: 3000,
      circle: 6,
      mode: "ease-in-out"
    };
  
    const targetAngle = angleList.value[index];
    const angle = rotateAngle.value + config.circle * CIRCLE_ANGLE + targetAngle - (rotateAngle.value % CIRCLE_ANGLE);
    rotateAngle.value = angle;
  
    
    setTimeout(() => {
      isRotating.value = false;
      remainingAttempts.value = 0;
    //   ElMessage.success(prizeList.value[index].prize_name); // 提示获奖
      console.log(prizeList.value[index].prize_name);
      goods.value = prizeList.value[index].prize_name
      goods_img.value = prizeList.value[index].prize_img
      prize_type.value = prizeList.value[index].prize_type

      if(prizeList.value[index].prize_type == 3){
        getUserInfo()
        getAwards_result_log()
        // getShow_awards_log()
        return
      } 
      isShow.value = true

      getUserInfo()
      getAwards_result_log()
      // getShow_awards_log()
    }, config.duration + 500);
  };
  
  onMounted(() => {
    // prizeAddHtml();
  });

  const isShow = ref(false);
  const isNav = ref(0)

  const awards_result_log_list = ref([])
  const getAwards_result_log = async ()=>{
    const res = await axios.get(`/awards_result_log?user_id=${user_info.id}`)
    awards_result_log_list.value = res.data
  }
  getAwards_result_log()



  const generateRandomNickname = () => {
    const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let nickname = '';
    const length = Math.floor(Math.random() * 6) + 5; // 随机长度在 5 到 10 之间
    for (let i = 0; i < length; i++) {
      nickname += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return nickname;
  }

  const prizeOptions = ['0.99滿減券', '4.99滿減券', '9.99滿減券'];
  let prize_data = ref([]);
  for (let i = 0; i < 500; i++) {
    prize_data.value.push({
      nickname: generateRandomNickname(),
      prize_name: prizeOptions[Math.floor(Math.random() * prizeOptions.length)]
    });
  }
  // console.log(prize_data.value);
    // const show_awards_log_list = ref([])
  // const getShow_awards_log = async ()=>{
  //   const res = await axios.get(`/show_awards_log`)
  //   show_awards_log_list.value = res.data
  // }
  // getShow_awards_log()

  const closeBox = () =>{
    isShow.value = false

    if(prize_type.value !== 2) return
    const data = {
      nickname:user_info.nickname,
      prize_name:goods.value,
    }

    prize_data.value = []
    for (let i = 0; i < 500; i++) {
      prize_data.value.push({
        nickname: generateRandomNickname(),
        prize_name: prizeOptions[Math.floor(Math.random() * prizeOptions.length)]
      });
    }

    prize_data.value.unshift(data)
    // console.log(prize_data.value);
    setTimeout(() => {
      prize_data.value.shift()
      // console.log(prize_data.value);
    }, 5000);
    
  }
  </script>
  
  <style lang="less" scoped>
  .img_box{
    position: fixed;
    top:50%;
    left: 50%;
    transform: translate(-50%,-50%) scale(0);
    transition:all .3s;
    z-index: 9999;
    background-color: white;
    border-radius: 15px;
    text-align: center;
    box-shadow: 1px 3px 10px 3px #00000069;
    img{
      display: block;
    }
    .close_box{
        position: absolute;
        right: 12px;
        top: 5px;
        cursor: pointer;
        transition: all .2s;
    }
    .close_box:hover{
        transform: scale(1.1);
    }
    h1{
        text-align: center;
        color: #fff;
        padding: 40px 20px;
        
    }
    p{
        text-align: center;
        color: white;
        position: relative;
        top: 150px;
        opacity: .7;
    }
    .top{
      background: linear-gradient(to right, #db6de7, #9b24c6);
      border-radius: 15px 15px 0 0;
    }
    .btn{
      padding: 8px 66px;
      background: linear-gradient(to right, #db6de7, #9b24c6);
      border: none;
      border-radius: 8px;
      color: white;
      margin-bottom: 20px;
      font-size: 23px;
      cursor: pointer;
    }
    .btn:hover{
      opacity: .8;
    }
  }
  .show{
        transform: translate(-50%,-50%) scale(1);
    }
  .blocker2 {
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 1001;
    position: fixed;
    top: 0;
    left: 0;
    text-align: center;
    
    
}
  /* 大转盘 */
  .luckBg {
    width: 400px;
    height: 400px;
    background-size: contain;
    margin: 20px 0;
    margin-bottom: 30px;
    box-sizing: border-box;
    position: relative;
    left: 50%;
    transform: translate(-50%);
  }
  
  .luckBg .luckWhellBg,
  .luckBg .luckWhellBgMain {
    background: pink;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    position: relative;
    overflow: hidden;
    box-shadow: 1px 3px 10px 3px rgba(0, 0, 0, 0.3);
  }
  
  .luckBg .luckWhellBg .rotateStyle,
  .luckBg .luckWhellBgMain .rotateStyle {
    -webkit-transition: transform 3000ms ease-in-out;
    transition: transform 3000ms ease-in-out;
  }
  
  .luckWhellSector {
    position: absolute;
    top: 0;
    right: 0;
    transform-origin: 0% 100%;
    border: 1px solid #9b24c6;
    border-right: 0;
    border-top: 0;
    box-sizing: border-box;
  }
  .luckWhellSector:nth-child(odd){
    background: rgb(181, 48, 229);
  }
  .luckWhellSector:nth-child(even){
    background: #db6de7;
  }
  
  .wheel-main {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
    transform: scale(0.9);
  }
  
  .prize-list {
    width: 100%;
    height: 100%;
    position: relative;
    
  }
  
  .prize-item {
    position: absolute;
    left: 50%;
    height: 50%;
    padding-top: 15px;
    box-sizing: border-box;
    text-align: center;
    transform-origin: 50% 100%;
    color: white;
    .prize_text{
      letter-spacing:0.05rem;
    }
    .img{
        margin-top: -5px;
        filter: brightness(1.15) saturate(1.15);
    }
  }
  
  .prize_point {
    position: absolute;
    left: 50%;
    width: 181px;
    background-size: contain;
    height: 220px;
    top: 50%;
    margin-left: -90px;
    margin-top: -100px;
    border-radius: 50%;
    text-align: center;
    line-height: 220px;
    font-size: 30px;
    cursor: pointer;
  }
  
  .jihui {
    text-align: center;
    margin-top: 20px;
  }
  .truntable_bg_en{
    background-image: url(../../assets/turntable_en.png) !important;
  }
  .truntable_bg {
    width: 100%;
    height: 100%;
    background-image: url(../../assets/turntable.png);
    background-size: cover;
    background-repeat: no-repeat;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 99999;
    cursor: pointer;
    }

    .tip{
        margin-top: 30px;
        h3{
            margin-top: 20px;
            margin-bottom: 7px;
        }
        ol{
            li{
                margin-bottom: 5px;
            }
        }
    }
    .xxcy{
      width: 70px;
      margin-top: 10px;
      font-size: 25px;
    }
    .progress{
      position: relative;
      width: 50%;
      border: 4px solid transparent;
      border-radius: 20px;
      background: linear-gradient(45deg, #ffe886, #ffe191, #f2c756, #e4ca2e, #f2c756, #f2c756, #ffe191, #ffe191, #e7be4f, #ffe191) border-box;
      background-clip: border-box;
      span{
        position: absolute;
        right: -70px;
        top: -1px;
        font-family: fantasy;
        transform: skew(-14deg, 0deg);
        background: linear-gradient(to top, #fdcaf0, #ff5abf 70%);
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
        font-size: 22px;
      }
    }
    nav{
      display: flex;
      margin-top: 20px;
      align-items: center;
      p{
        cursor: pointer;
        margin: 0;
        margin-right: 20px;
        font-weight: bold;
        font-size: 20px;
        opacity: 0.6;
        padding-bottom: 5px;
      }
      .active{
        font-size: 27px !important;
        opacity: 1;
        border-bottom: 12px solid rgb(219, 109, 231);
      }
    }
    .recharge_content{
      margin-top: 25px;
      .title{
          display: flex;
          padding: 10px 0;
          border-bottom: 1px solid rgba(0, 0, 0, 0.1);
          span{
              flex: 1;
              text-align: center;
          }
      }
      .main{
        height: 420px;
        overflow: auto;
        .main_line{
            span{
                flex: 1;
                text-align: center;
            }
            display: flex;
            padding: 10px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        align-items: center;
            .btn{
                cursor: pointer;
            }
            .green{
                color: #15b300;
            }
            .red{
                color: red;
            }
        }
      }
    }
    .carousel-box{
      margin-top: 30px;
      .carousel{
        text-align: center;
        font-size: 13px;
      }
    }
    
  </style>
  
  
  